package com.wang.service;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.wang.bo.PayBo;
import com.wang.entity.Cart;
import com.wang.entity.PayInfo;
import com.wang.entity.Product;
import com.wang.mapper.CartMapper;
import com.wang.mapper.PayInfoMapper;
import com.wang.mapper.ProductMapper;
import com.wang.util.OrderNo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Classname PayService
 * @Description TODO
 * @Date 2025/3/25 9:46
 * @Created by pc
 */
@Service
public class PayService {
    @Value("${alipay.returnUrl}")
    private String returnUrl;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Object pay(PayBo bo) throws Exception {
        // 生成订单号
        String orderNo = OrderNo.getOrderNo();
        System.out.println("订单号:" + orderNo);
        // 存redis    key 订单号  value userId
        stringRedisTemplate.opsForValue().set(orderNo,bo.getUserId().toString());
        // 调用支付宝接口支付
        AlipayTradePagePayResponse response = Factory.Payment.Page()
                .pay(bo.getSubject(), orderNo, bo.getTotal().toString(), returnUrl);
        return response.body;
    }

    @Resource
    private CartMapper cartMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private PayInfoMapper payInfoMapper;
    @Transactional(propagation = Propagation.REQUIRED)
    public void updatePayStatus(Map<String, String[]> map) {
        String orderNo = map.get("out_trade_no")[0];
        // 1.修改库存
        // 从redis中获取用户编号 有证明订单存在 没有证明订单不存在
        Integer userId = Integer.parseInt(stringRedisTemplate.opsForValue().get(orderNo));
        // 根据用户编号获取 用户购买的商品 -- cart中选中的商品
        List<Cart> cartBuyList = cartMapper.findCartByUserIdAndBuyed(userId);
        // 遍历 并修改库存
        cartBuyList.forEach(cart -> {
            Integer productId = cart.getProductId();
            Integer quantity = cart.getQuantity();
            // // 根据商品id 去查找 商品 然后修改 库存
            Product product = productMapper.findById(productId);
            // 减少库存
            product.setStock(product.getStock() - quantity);
            // 更新数据库
            productMapper.updateStock(product);
        });
        // 删除结算商品
        cartMapper.deleteBuyed(userId);
        // 添加支付订单
        PayInfo payInfo = new PayInfo();
        payInfo.setUserId(userId);
        payInfo.setOrderNo(Long.parseLong(orderNo));
        payInfo.setPayPlatform(1);
        payInfo.setPlatformNumber(map.get("trade_no")[0]);
        payInfo.setPlatformStatus(map.get("trade_status")[0]);
        payInfo.setCreateTime(new Date());
        payInfo.setUpdateTime(new Date());
        payInfoMapper.add(payInfo);
        // 删除redis
        stringRedisTemplate.delete(orderNo);
    }
}
